import pymysql
from frameworks.cores.Config import *
from frameworks.utils.LogUtil import *

class DB:
    db = ''
    cursor = ''

    def __init__(self,db="cloud_data"):
        basepath = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
        config = Config(basepath)
        if db == "cloud_data":
            conf = config.getCloudDataDB()
        else:
            conf = config.getCloudDeskDB()
        print(conf)
        self.db = pymysql.connect(host=conf[0],user=conf[1],password=conf[2],port=conf[3],database=conf[4],charset='utf8')
        self.current = os.path.abspath(os.path.join(os.getcwd(), "../.."))
        print(self.current)
        self.cursor = self.db.cursor()
        sys_platform = platform.platform().lower()
        if sys_platform.find("windows") >= 0:
            self.logdir = self.current + "logs\\"
        else:
            self.logdir = self.current + "logs/"
        print(self.logdir)
        self.log = LogUtil(self.logdir, "sql")

    def getCloudDeskDB(self,db="cloud_data"):
        basepath = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
        config = Config(basepath)
        if db == "cloud_data":
            conf = config.getCloudDataDB()
        else:
            conf = config.getCloudDeskDB()
        return conf

    def executeSql(self,sql=''):
        try:
            self.log.writeLog(sql)
            # 执行SQL语句
            result = self.cursor.execute(sql)
            # print(result)
            # 获取所有记录列表
            results = self.cursor.fetchall()
            # print(results)
            if not results:
                results = None
        except:
            print("Error: unable to fecth data")
            results = False

        return results

    def executeSqlMap(self,sql='',table="",addField=[]):
        self.log.writeLog(sql)
        rs = self.executeSql(sql)
        colrs = self.executeSql("desc " + table)
        field = []
        for cols in colrs:
            field.append(cols[0])
        if len(addField) > 0:
            for col in addField:
                field.append(col)
        newrs = []
        if rs != None and rs != False and len(rs) > 0:
            for row in rs:
                option = {}
                for i in range(len(row)):
                    option[field[i]] = row[i]
                newrs.append(option)
        return newrs

    def addOnly(self,sql):
        try:
            self.log.writeLog(sql)
            self.cursor.execute(sql)
            # 提交到数据库执行
            self.db.commit()
            return ""
        except:
            self.db.rollback()
            print("Error: add error")
            return False

    def add(self,sql):
        try:
            self.log.writeLog(sql)
            self.cursor.execute(sql)
            # 提交到数据库执行
            self.db.commit()
            return self.cursor.lastrowid
        except:
            self.db.rollback()
            print("Error: add error")
            return False

    def update(self,sql):
        try:
            self.log.writeLog(sql)
            self.cursor.execute(sql)
            # 提交到数据库执行
            self.db.commit()
            return True
        except:
            self.db.rollback()
            print("Error: update error")
            return False

    def update_more(self,sql_list):
        try:
            for sql in sql_list:
                self.log.writeLog(sql)
                self.cursor.execute(sql)
            self.db.commit()
            return True
        except:
            self.db.rollback()
            print("Error: update error")
            return False

    def delete(self,sql):
        try:
            self.log.writeLog(sql)
            result = self.cursor.execute(sql)
            # 提交到数据库执行
            self.db.commit()
            result = True
        except:
            self.db.rollback()
            result = False
            print("Error: delete error")
        return result


